package com.googlecode.olabs.gui.client.rest;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;

public class RestRequestBuilder extends RequestBuilder {

	public static final class Method {

		public static final String GET = "get";
		public static final String PUT = "put";
		public static final String POST = "post";
		public static final String DELETE = "delete";
		public static final String HEAD = "head";

		private final String m_name;

		private Method(String name) {
			m_name = name;
		}

		@Override
		public String toString() {
			return m_name;
		}
	}

	public static final Method GET = new Method(Method.GET);
	public static final Method POST = new Method(Method.POST);
	public static final Method PUT = new Method(Method.PUT);
	public static final Method DELETE = new Method(Method.DELETE);
	public static final Method HEAD = new Method(Method.HEAD);

	public static RestRequestBuilder create(final Method method,
			final String url) {
		return create(method, url, null);
	}

	public static RestRequestBuilder create(final Method method,
			final String url, final String contents) {
		RestRequestBuilder builder;
		if (method == GET) {
			return new RestRequestBuilder(method, RequestBuilder.GET, url, null);
		} else if (method == POST) {
			return new RestRequestBuilder(method, RequestBuilder.POST, url,
					contents);
		} else if (method == PUT) {
			return new RestRequestBuilder(method, RequestBuilder.POST,
					addFakeUrlArgument(url, Method.PUT), contents);
		} else if (method == HEAD) {
			return new RestRequestBuilder(method, RequestBuilder.GET,
					addFakeUrlArgument(url, Method.HEAD), null);
		} else if (method == DELETE) {
			return new RestRequestBuilder(method, RequestBuilder.GET,
					addFakeUrlArgument(url, Method.DELETE), null);
		} else {
			return null;
		}
	}

	private static String addFakeUrlArgument(final String url,
			final String fakeMethodType) {
		final String FAKE_POST_VARIABLE = "fakeMethod";
		if (url.contains("?")) {
			return url + "&" + FAKE_POST_VARIABLE + "=" + fakeMethodType;
		} else {
			return url + "?" + FAKE_POST_VARIABLE + "=" + fakeMethodType;
		}
	}

	private String m_contents;
	private Method m_method;

	private RestRequestBuilder(final Method method,
			final RequestBuilder.Method trueMethod, final String url,
			final String contents) {
		super(trueMethod, url);
		m_method = method;
		m_contents = contents;
	}

	public Request sendRequest(RequestCallback callback)
			throws RequestException {
		return super.sendRequest(m_contents, callback);
	}
}
